<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { OrganizationVO, UpdateRequest } from '@/api/Organization.ts'
import { OrganizationApi } from '@/api/OrganizationApi.ts'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import { message } from 'ant-design-vue'

const props = defineProps<{
  organization: OrganizationVO
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'success'): void
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive<UpdateRequest>({
  id: props.organization.id,
  name: props.organization.name,
  description: props.organization.description,
})

// 表单校验规则
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    {
      validator: (_, value) => {
        if (!value) return Promise.resolve()
        if (value.length < 2 || value.length > 50) {
          return Promise.reject(new Error('组织名称长度2-50位'))
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  description: [
    { required: true, message: '请输入组织描述', trigger: 'blur' },
    {
      validator: (_, value) => {
        if (!value) return Promise.resolve()
        if (value.length < 2) {
          return Promise.reject(new Error('描述长度至少2位'))
        }
        if (value.length > 500) {
          return Promise.reject(new Error('描述长度不能超过500位'))
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

const onSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch (error) {
    console.error('表单校验失败:', error)
    return
  }

  try {
    loading.value = true
    const success = await OrganizationApi.update(form)
    if (success) {
      message.success('修改成功')
      emit('success')
      emit('close')
    } else {
      message.error('修改失败')
    }
  } catch (error) {
    message.error('修改失败：' + (error as any)?.message || '未知错误')
  } finally {
    loading.value = false
  }
}
</script>

<template>
<a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
  <a-form-item label="组织名称" name="name">
    <a-input v-model:value="form.name" placeholder="输入组织名称" />
  </a-form-item>
  <a-form-item label="组织描述" name="description">
    <a-textarea v-model:value="form.description" :rows="5" placeholder="输入组织描述" />
  </a-form-item>
  <a-space>
    <a-button type="primary" :loading="loading" @click="onSubmit">保存</a-button>
    <a-button @click="$emit('close')">取消</a-button>
  </a-space>
</a-form>
</template>

<style scoped>

</style>
